package com.xls.box2023.manager;

import android.app.Activity;
import android.text.TextUtils;
import android.view.View;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzz.bottomencapsulation.consts.NetConsts;
import com.lzz.bottomencapsulation.eventbus.MessageEvent;
import com.lzz.bottomencapsulation.net.RequestCallBack;
import com.lzz.bottomencapsulation.utils.AppUtils;
import com.lzz.bottomencapsulation.utils.LUtils;
import com.lzz.bottomencapsulation.utils.TUtils;
import com.xls.box2023.Consts.EventCode;
import com.xls.box2023.Consts.StateConsts;
import com.xls.box2023.R;
import com.xls.box2023.entity.UserEntity;
import com.xls.box2023.entity.YouXiEntity;
import com.xls.box2023.home.DownloadApkUtils;
import com.xls.box2023.home.HomeNetWorkUtil;
import com.xls.box2023.home.XiaoHaoJiFenYouXiDialog;
import com.xls.box2023.wxshare.WxShareUtils;
import com.xls.resource.dialog.utils.download.DownloadListener;
import com.xls.resource.dialog.utils.download.DownloadUtils;
import com.xls.resource.dialog.utils.download.PackageUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * @author lhx
 * @description:
 * @date : 2024/3/15 14:15
 */
public class APKDownLoadManager {
    private static volatile  APKDownLoadManager instance;

    private APKDownLoadManager() {

    }

    public static APKDownLoadManager getInstance() {
        if (instance == null) {
            synchronized (APKDownLoadManager.class) {
                if (instance == null) {
                    instance = new APKDownLoadManager();
                }
            }
        }
        return instance;
    }

    /**
     *开始下载
     */
    public void start(Activity activity, YouXiEntity youXi){
        String state=getAPKState(youXi.getAppId());
        if (TextUtils.equals(state,State.stop)){
//            开始走下载流程，step1：判断是否需要扣除金币，是否已经扣除金币
            APKDownLoadEntity apkDownLoadEntity=new APKDownLoadEntity(youXi.getAppId(),
                    youXi.getFilePath(),youXi.getDownStatus(),youXi.getDownCoins(),youXi.getFileName(),youXi.getJksName());
                downloadData.remove(apkDownLoadEntity.getAppid());
                getPermissions(activity,apkDownLoadEntity);
        }else if (TextUtils.equals(state,State.ok)){
            AppUtils.anZhuangAPk(activity,youXi.getFilePath());
        }else {
            stateToast(activity,state);
        }
    }

    private void stateToast(Activity activity, String state){
        if (TextUtils.equals(state,APKDownLoadManager.State.generateing)){
            TUtils.showShort(activity,"获取中～");
        } else if (TextUtils.equals(state,APKDownLoadManager.State.downloading)){
            TUtils.showShort(activity,"下载中～");
        }
    }

    public void stopAll(){
        downloadData.clear();
    }

    /**
     * 获取apk的状态
     */
    public String getAPKState(Long appid){
        APKDownLoadEntity youXi=  downloadData.get(appid);
        if (youXi==null){
            return State.stop;
        }else {
            if (TextUtils.equals(youXi.getDownLoadState(),State.ok)){
                File file=new File(youXi.getFilePath());
                if (file.exists()&&file.length()==youXi.getFileSize()&& PackageUtil.computeMD5(new File(youXi.getFilePath())).toUpperCase().equals(youXi.getFileMd5().toUpperCase())){
                    return State.ok;
                }else {
                    downloadData.remove(appid);
                    return State.stop;
                }
            }
        }
        return youXi.getDownLoadState();
    }


    HashMap<Long, APKDownLoadEntity> downloadData=new HashMap<>();//下载对象管理

    /**
     * 是否正在下载中
     * @return
     */
    public boolean isDownLoading(String appid){
        if (downloadData.get(appid)==null)return false;
        else return true;
    }

    public APKDownLoadEntity getAPKDownLoad(long appId) {
        return downloadData.get(appId);
    }


    public interface State{
        String generateing="generateing";//生成包中
        String downloading="downloading";//下载中
        String ok="ok";//下载完成
        String stop="stop";//未下载
    }


    private void getPermissions(Activity activity,   APKDownLoadEntity youXi) {
        XXPermissions.with(activity)
                // 申请单个权限
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            showYouXiXiaoHaoJiFenDialog(activity,youXi);//判断是否需要扣除金币
                        }else {
                            TUtils.showShort(activity,"请授予全部权限否则无法下载");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            XXPermissions.startPermissionActivity(activity, permissions);
                        } else {
                            TUtils.showShort(activity,"请授予权限否则无法下载");
                        }
                    }
                });
    }
    /**
     * 显示游戏消耗积分的确认弹窗
     */
    private void showYouXiXiaoHaoJiFenDialog(Activity activity,   APKDownLoadEntity youXi) {
        startDownLoad(youXi,State.generateing,0);//开启状态
        if (youXi.getDownCoins() > 0 && youXi.getDownStatus() != StateConsts.DowmStatus.ok) {
            XiaoHaoJiFenYouXiDialog xiaoHaoJiFenYouXiDialog = new XiaoHaoJiFenYouXiDialog(activity, youXi.getDownCoins(), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int id = view.getId();
                    if (id == R.id.dialog_tv_download) {
                        getDownLoadUrl(activity,youXi);
                    } else {
                        stopDownload(youXi);
                    }
                }
            });
            xiaoHaoJiFenYouXiDialog.show();
        } else {
            getUserAgentInfo(activity,youXi);
        }

    }

    private void startDownLoad(APKDownLoadEntity apkDownLoadEntity, String state,int progress) {
        apkDownLoadEntity.setDownLoadState(state);
        apkDownLoadEntity.setPrross(progress);
        EventBus.getDefault().post(new MessageEvent(EventCode.code_state_chanage,apkDownLoadEntity));
        downloadData.put(apkDownLoadEntity.getAppid(), apkDownLoadEntity);
    }

    private void downLoading(APKDownLoadEntity apkDownLoadEntity, int progress) {
        LUtils.e("下载中"+progress);
        apkDownLoadEntity.setDownLoadState(State.downloading);
        apkDownLoadEntity.setPrross(progress);
        EventBus.getDefault().post(new MessageEvent(EventCode.code_state_chanage,apkDownLoadEntity));
    }


    /**
     * 扣除金币接口
     */
    private void getDownLoadUrl(Activity activity,APKDownLoadEntity youXi){
        HomeNetWorkUtil.getInstance().getAPKURL(youXi.getAppid()+"", new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {
            }

            @Override
            public void onRequestSuccess(String requestData) {
                getUserAgentInfo(activity,youXi);
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                TUtils.showShort(activity,errmsg);
                stopDownload(youXi);
            }

        });
    }

    /**
     * 停止下载
     */
    private void stopDownload(APKDownLoadEntity apkDownLoadEntity) {
        apkDownLoadEntity.setDownLoadState(State.stop);
        EventBus.getDefault().post(new MessageEvent(EventCode.code_state_chanage,apkDownLoadEntity));
        DownloadApkUtils.getInstance().remove(apkDownLoadEntity.getAppid());
    }

    private void okDownload(APKDownLoadEntity apkDownLoadEntity) {
        apkDownLoadEntity.setDownLoadState(State.ok);
        EventBus.getDefault().post(new MessageEvent(EventCode.code_state_chanage,apkDownLoadEntity));
    }


    private void getUserAgentInfo(Activity activity,APKDownLoadEntity apkDownLoadEntity) {
        HomeNetWorkUtil.getInstance().getUserAgentInfo(new RequestCallBack<UserEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(UserEntity requestData) {
                String channel=requestData.getUserId();
                apkDownLoadEntity.setChannel(channel);
                if (TextUtils.isEmpty(channel)){
                    stopDownload(apkDownLoadEntity);
                    TUtils.showShort(activity,"没有上级联系人，无法下载游戏，请联系游戏代理");
                }else {
                    getAPKQuDaoBao(activity,apkDownLoadEntity);
                }
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                TUtils.showShort(activity,errmsg);
                stopDownload(apkDownLoadEntity);
            }
        });
    }


    /*
 生成渠道包
  */
    private void getAPKQuDaoBao(Activity activity,APKDownLoadEntity apkDownLoadEntity) {
        WxShareUtils.getInstance().getUserCode2(new RequestCallBack<YouXiEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {
            }

            @Override
            public void onRequestSuccess(YouXiEntity requestData) {
                apkDownLoadEntity.setUrl(requestData.getDownloadUrl());
                apkDownLoadEntity.setFileMd5(requestData.getMd5());
                apkDownLoadEntity.setFileSize(requestData.getFileSize());
                download(activity,apkDownLoadEntity);
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                stopDownload(apkDownLoadEntity);
            }
        },apkDownLoadEntity.getFileName(), apkDownLoadEntity.getChannel(),apkDownLoadEntity.getJksName());
    }

    public void download(Activity activity,APKDownLoadEntity apkDownLoadEntity) {
        DownloadUtils down=new DownloadUtils(NetConsts.BASE_COM_URL,apkDownLoadEntity.getAppid(), new DownloadListener() {
            @Override
            public void onStartDownload(long id) {
                startDownLoad(apkDownLoadEntity,State.downloading, 0);
            }

            @Override
            public void onProgress(long id, int progress) {
                downLoading(apkDownLoadEntity,progress);
            }

            @Override
            public void onFinishDownload(long id) {
                okDownload(apkDownLoadEntity);
            }

            @Override
            public void onFail(long id, String errorInfo) {
                okDownload(apkDownLoadEntity);
            }

            @Override
            public void onError(long id, String errorInfo) {
                stopDownload(apkDownLoadEntity);
            }

            @Override
            public void onComplete(Long id) {
                okDownload(apkDownLoadEntity);
            }
        });
        down.downloadAPK(apkDownLoadEntity.getAppid(),apkDownLoadEntity.getUrl(), apkDownLoadEntity.getFilePath());
        DownloadApkUtils.getInstance().addDownLoad(apkDownLoadEntity.getAppid(),down);
    }

}

